package com.zl.quickdoc.format.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zl.quickdoc.constant.QuickDocC;
import com.zl.quickdoc.format.FreemarkerTemplater;
import com.zl.quickdoc.format.IApiFormat;
import com.zl.quickdoc.model.ApiDocument;
import com.zl.quickdoc.model.ApiModule;
import com.zl.quickdoc.model.DocCfgParam;
import com.zl.quickdoc.utils.JsonUtils;
import com.zl.quickdoc.utils.SplitListUtils;

/**
 * @author zhouliang
 */
public class ApiFormatHtml extends ApiFormatBase implements IApiFormat {

    private FreemarkerTemplater templater = new FreemarkerTemplater("classpath:"+QuickDocC.TEMPLATE_ROOT+QuickDocC.TEMPLATE_HTML);
    
    @Override
    public String formatType() {
        return QuickDocC.DOC_TYPE_HTML;
    }
    @Override
    public String templateName() {
        return QuickDocC.TEMPLATE_HTML;
    }
    
    @Override
    public void format(ApiDocument apiDoc,DocCfgParam cfg) throws Exception {
        File tFile = getTemplatePath(cfg, templateName());
        if(tFile.exists()&&tFile.isFile()) {
            templater.setPath(tFile.getPath());
        }
        
        Map<String, Object> model = new HashMap<>();
        model.putAll(apiDoc.getProperties());
        model.put("changeList", joinChangeContent(apiDoc.getChangedata(),";;  ","<br>","&nbsp;&nbsp;&nbsp;&nbsp;"));
        List<List<ApiModule>> splitApiModules = SplitListUtils.split(apiDoc.getApiModules(), this.getSplitNum(cfg));
        for(int i=0;i<splitApiModules.size();i++){
            model.put("apiModules", splitApiModules.get(i));
            model.put("json_models", JsonUtils.toJson(model));
            String s2 = templater.processString(model);
            String filename= i + ".html";
            File outfile = new File(cfg.getApiPath(), this.getFileTitle(cfg)+filename);
            FileOutputStream out = new FileOutputStream(outfile);
            writeDoc(s2, out);
            if(i==0) {
                apiDoc.setOutputPath(outfile.getAbsolutePath());
            }
        }
    }
}
